package com.projectx.adpter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.projectx.R;
import com.projectx.entity.ChatData;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ChatDataAdapter extends RecyclerView.Adapter<ChatDataAdapter.VH> {
    private Context context;
    private TextView content;
    private List<ChatData> chatData;
    private String username;

    public ChatDataAdapter(Context context, List<ChatData> chatData, String username){
        this.context = context;
        this.chatData = chatData;
        this.username = username;
    }
    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_one_chat_data,parent,false);
        return new VH(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final VH holder, final int position) {
        String nowName = chatData.get(position).getSendUser();//这里数据库会大改
        SharedPreferences sharedPreferences = context.getSharedPreferences("chat_setting",Context.MODE_PRIVATE);
        int myColor = sharedPreferences.getInt("myColor", Color.BLACK);
        int otherColor = sharedPreferences.getInt("otherColor",Color.BLACK);
        GradientDrawable gradientDrawable = (GradientDrawable) holder.broader.getBackground().mutate();
        if (nowName.equals(username)){
            gradientDrawable.setStroke(4,myColor);
            holder.direction.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        } else {
            gradientDrawable.setStroke(4,otherColor);
            holder.direction.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
        }
        holder.time.setText(chatData.get(position).getTime().toString());
        //为ImageView设置点击事件
        if (chatData.get(position).getImageUri() != null){
            holder.imageInsert.setVisibility(View.VISIBLE);
            holder.imageInsert.setImageURI(chatData.get(position).getImageUri());

            holder.imageInsert.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final PopupWindow popupWindow = new PopupWindow(context);
                    popupWindow.setBackgroundDrawable(context.getDrawable(R.drawable.bg_shadow_white));
                    View view = LayoutInflater.from(context).inflate(R.layout.item_menu_chat_data,null,false);
                    view.findViewById(R.id.delete_data).setOnClickListener(new View.OnClickListener() {//设置删除监听
                        @Override
                        public void onClick(View v) {
                            chatData.remove(position);
                            notifyItemRemoved(position);
                            notifyItemRangeChanged(position,getItemCount());
                            popupWindow.dismiss();
                        }
                    });
                    if (chatData.get(position).getRecord().length() > 0) { //复制按钮
                        TextView copyText = view.findViewById(R.id.copy_text);
                        copyText.setVisibility(View.VISIBLE); //恢复复制选项可见性
                        copyText.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) { //设置复制监听
                                ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData clipData = ClipData.newPlainText("", chatData.get(position).getRecord());
                                if (cm != null) {
                                    cm.setPrimaryClip(clipData);
                                    Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context, "复制失败", Toast.LENGTH_SHORT).show();
                                }
                                popupWindow.dismiss();
                            }
                        });
                    }
                    if (chatData.get(position).getImageUri() != null){
                        TextView saveImage = view.findViewById(R.id.save_image);
                        saveImage.setVisibility(View.VISIBLE);
                        saveImage.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(chatData.get(position).getImageUri(),"r");
                                    FileDescriptor fd = fileDescriptor.getFileDescriptor();
                                    FileInputStream fis = new FileInputStream(fd);//文件输入流
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
                                    final String format = sdf.format(new Date());
                                    final File file = new File(Environment
                                            .getExternalStorageDirectory().toString()
                                            + "/ProjectX/"
                                            + format
                                            + ".png");
                                    FileOutputStream fos = new FileOutputStream(file);
                                    byte[] flush = new byte[1024];
                                    int len = -1;
                                    while ((len = fis.read(flush)) != -1) {
                                        fos.write(flush,0,len);
                                    }
                                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                                    Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
                                } catch (Exception e){
                                    e.printStackTrace();
                                    Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                                }
                                popupWindow.dismiss();
                            }
                        });
                    }


                    popupWindow.setContentView(view);
                    popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.showAsDropDown(v,0,0);
                    return true;
                }
            });
            holder.imageInsert.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final ImageView bigImage = new ImageView(context);
                    bigImage.setBackgroundColor(Color.TRANSPARENT);
                    bigImage.setImageURI(chatData.get(position).getImageUri());
                    final WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);//调用windowmanage显示图片
                    WindowManager.LayoutParams wmParams=new WindowManager.LayoutParams();
                    wmParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                    wmParams.format= PixelFormat.TRANSPARENT; //set the opacity to 100%
                    wmParams.windowAnimations=android.R.style.Animation_Translucent;
                    wm.addView(bigImage,wmParams);
                    bigImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            wm.removeViewImmediate(bigImage);
                        }
                    });
                    bigImage.setOnKeyListener(new View.OnKeyListener() {
                        @Override
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            wm.removeViewImmediate(bigImage);
                            return true;
                        }
                    });
                }
            });

        }
        else {
            holder.imageInsert.setVisibility(View.GONE);
        }
        //装配Data
        if (chatData.get(position).getRecord() != null){
            holder.data.setText(chatData.get(position).getRecord());
        } else {
            holder.data.setText("");
        }
        holder.broader.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final PopupWindow popupWindow = new PopupWindow(context);
                popupWindow.setBackgroundDrawable(context.getDrawable(R.drawable.bg_shadow_white));
                View view = LayoutInflater.from(context).inflate(R.layout.item_menu_chat_data,null,false);
                view.findViewById(R.id.delete_data).setOnClickListener(new View.OnClickListener() {//设置删除监听
                    @Override
                    public void onClick(View v) {
                        chatData.remove(position);
                        notifyItemRemoved(position);
                        notifyItemRangeChanged(position,getItemCount());
                        popupWindow.dismiss();
                    }
                });
                if (chatData.get(position).getRecord().length() > 0) { //复制按钮
                    TextView copyText = view.findViewById(R.id.copy_text);
                    copyText.setVisibility(View.VISIBLE); //恢复复制选项可见性
                    copyText.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) { //设置复制监听
                            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                            ClipData clipData = ClipData.newPlainText("", chatData.get(position).getRecord());
                            if (cm != null) {
                                cm.setPrimaryClip(clipData);
                                Toast.makeText(context, "复制成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context, "复制失败", Toast.LENGTH_SHORT).show();
                            }
                            popupWindow.dismiss();
                        }
                    });
                }
                if (chatData.get(position).getImageUri() != null){
                    TextView saveImage = view.findViewById(R.id.save_image);
                    saveImage.setVisibility(View.VISIBLE);
                    saveImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(chatData.get(position).getImageUri(),"r");
                                FileDescriptor fd = fileDescriptor.getFileDescriptor();
                                FileInputStream fis = new FileInputStream(fd);//文件输入流
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
                                final String format = sdf.format(new Date());
                                final File file = new File(Environment
                                        .getExternalStorageDirectory().toString()
                                        + "/ProjectX/"
                                        + format
                                        + ".png");
                                FileOutputStream fos = new FileOutputStream(file);
                                byte[] flush = new byte[1024];
                                int len = -1;
                                while ((len = fis.read(flush)) != -1) {
                                    fos.write(flush,0,len);
                                }
                                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                                Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
                            } catch (Exception e){
                                e.printStackTrace();
                                Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
                            }
                            popupWindow.dismiss();
                        }
                    });
                }


                popupWindow.setContentView(view);
                popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.showAsDropDown(v,0,0);
                return true;
            }
        });

    }


    @Override
    public int getItemCount() {
        return chatData == null ? 0 : chatData.size();
    }

    public static class VH extends RecyclerView.ViewHolder{

        ImageView headImage;
        TextView data;
        TextView time;
        ImageView imageInsert;
        LinearLayout direction;//用来改变布局左右
        LinearLayout broader;
        public VH(@NonNull View itemView) {
            super(itemView);
            headImage = itemView.findViewById(R.id.head_image);
            time = itemView.findViewById(R.id.chat_time);
            data = itemView.findViewById(R.id.chat_content);
            direction = itemView.findViewById(R.id.single_data_direction);
            imageInsert = itemView.findViewById(R.id.imaged_inserted);
            broader = itemView.findViewById(R.id.chat_broader);
        }
    }
}
